package com.yunshipei.core.ui.client;

import android.annotation.SuppressLint;
import android.net.http.SslError;
import android.webkit.ValueCallback;

import org.xwalk.core.XWalkHttpAuthHandler;
import org.xwalk.core.XWalkView;

public class EnterWebViewClient extends BaseXWalkViewClient {

    final String ENCODING = "UTF-8";
    OnEnterWebViewClientInteractionListener mEnterWebViewClientInteractionListener;

    EnterWebViewClient(XWalkView view, OnEnterWebViewClientInteractionListener baseWebViewClientInteractionListener) {
        super(view);
        this.mEnterWebViewClientInteractionListener = baseWebViewClientInteractionListener;
    }

    @Override
    public void onProgressChanged(XWalkView view, int progressInPercent) {
        super.onProgressChanged(view, progressInPercent);
        if (mEnterWebViewClientInteractionListener != null) {
            mEnterWebViewClientInteractionListener.updateProgress(progressInPercent);
        }
    }

    @Override
    public void onReceivedSslError(XWalkView view, ValueCallback<Boolean> callback, SslError error) {
        callback.onReceiveValue(true);
    }

    @SuppressLint("CommitPrefEdits")
    @Override
    public void onReceivedHttpAuthRequest(XWalkView view, final XWalkHttpAuthHandler handler, final String host, String realm) {
        if (mEnterWebViewClientInteractionListener != null && !mEnterWebViewClientInteractionListener.onReceivedEnterHttpAuthRequest(view, handler, host, realm)) {
            super.onReceivedHttpAuthRequest(view, handler, host, realm);
        }
    }

    @Override
    public void onReceivedLoadError(XWalkView view, int errorCode, String description, String failingUrl) {
        if (mEnterWebViewClientInteractionListener != null) {
            mEnterWebViewClientInteractionListener.onLoadFailed();
        }
        super.onReceivedLoadError(view, errorCode, description, failingUrl);
    }

    public interface OnEnterWebViewClientInteractionListener {
        /**
         * WebView进度变化回调
         */
        void updateProgress(int progress);

        /**
         * 在WebViewClient中的shouldOverrideUrlLoading方法中拦截到的url，如果能匹配到，则打开新的WebView加载适配
         *
         * @return true 匹配到适配方案， false没有匹配到适配方案
         */
        boolean matchOverrideUrl(String url);

        /**
         * WebView加载出错
         */
        void onLoadFailed();

        /**
         * WebView地址栏地址变化回调
         *
         * @param url 新的url
         */
        void onWebViewUrlChanged(String url);

        /**
         * http认证接口
         */
        boolean onReceivedEnterHttpAuthRequest(XWalkView view, XWalkHttpAuthHandler handler, String host, String realm);

        /**
         * 是否是要自己处理shouldOverrideUrlLoading方法的这个url
         */
        boolean shouldLoadUrlSelf(XWalkView view, String url);
    }
}

